package cn.com.callback

import org.json.JSONArray;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.com.elite.EliteBean;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject

import com.huasheng.passwordencrypt.DecryptUtil

/**
 *
 * @Title: apiHSTEncTransFormMark
 * @Description:华盛证券  根据客户customer_guid 转换输出掩码 【手机号、邮箱、Whatsapp、】--内部接口
 * @author: cheih
 * @Date 2024/3/22 14:54
 *
 */

public class apiHSTEncTransFormMark implements ServiceBackInvoke {
        private static final Log log = LogFactory.getLog(apiHSTEncTransFormMark.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        String inData = "";
        String dataSourceID = "dataSource";


        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        JSONObject outData = new JSONObject();
        try {
            // 调用处理信息
            JSONObject inObject = new JSONObject(inData);

            def jsonarr = GetJV(inObject, "jsonarr");
            // 调用处理信息
            log.debug("解析信息-获取" + "jsonarr: " + jsonarr);

            JSONArray arrJsonArray = new JSONArray(jsonarr);
            int arrInt = arrJsonArray.length();
            log.debug("接入List权重数量:" + arrInt);

            String customer_guidlist="";
            String customer_guid;
            for (int i = 0; i < arrInt; i++) {
                JSONObject arrJson = arrJsonArray.getJSONObject(i);
                //获取信息
                customer_guid = GetJV(arrJson, "customer_guid");
                log.debug("接入 customer_guid:" + customer_guid);
                customer_guidlist=customer_guidlist+"','"+customer_guid;
            }
            //截去首位逗号
            customer_guidlist=customer_guidlist.substring(3);
            log.debug("接入 customer_guidlist:" + customer_guidlist);

            def selectcustlistSQL = "select customer_guid,mobile_enc,E_MAIL_enc,open_id_enc from customer  Where customer_guid in ('" + customer_guidlist + "')";
            def selectcustlistresult = eliteBean.chaxun_sql(selectcustlistSQL, "dataSource");

            def custlistcount = selectcustlistresult.size();
            log.debug("待处理的数量 custlistcount：" + custlistcount);

            String mobile_enc,E_MAIL_enc,open_id_enc="";//申明 enc
            String mobile,E_MAIL,open_id="";//申明明文
            String mobile_mark,E_MAIL_mark,open_id_mark="";//申明明文
            ArrayList markarray = new ArrayList();//申明返回
            int mobilelenth=0;
            int open_idlenth=0;
            String[] custarr;

            for (int j = 0; j <custlistcount; j++) {
                Map selectbrandMap = selectcustlistresult.get(j);
                customer_guid = selectbrandMap.get("customer_guid");
                mobile_enc = selectbrandMap.get("mobile_enc");
                E_MAIL_enc = selectbrandMap.get("E_MAIL_enc");
                open_id_enc = selectbrandMap.get("open_id_enc");

                if(mobile_enc==''||mobile_enc==null){
                    log.debug("mobile为空，密文解析为空！");
                    mobile_mark = "";
                }else{
                    try{
                        mobile = DecryptUtil.decrypt(mobile_enc);
                        //手机号：大陆手机号（前三后四明文，其余*展示）/非大陆手机号（前二后三明文，其他其余*展示）；
                        mobilelenth=mobile.length();
                        if(mobilelenth>=11){
                            mobile_mark=mobile.substring(0,3)+"****"+mobile.substring(mobilelenth-4,mobilelenth);
                        }else if(mobilelenth>=8){
                            mobile_mark=mobile.substring(0,2)+"***"+mobile.substring(mobilelenth-3,mobilelenth);
                        }else{
                            mobile_mark=mobile;
                        }
                    } catch (Exception e) {
                        log.error("mobile密文解析处理异常" + e.getMessage());
                        mobile_mark = "";
                    }
                }

                if(E_MAIL_enc==''||E_MAIL_enc==null){
                    log.debug("E_MAIL为空，密文解析为空！");
                    E_MAIL_mark = "";
                }else{
                    try{
                        E_MAIL = DecryptUtil.decrypt(E_MAIL_enc);
                        //邮箱账号： 邮箱只显示前4个字符和'@'之后的字符，前4个字符之后’@‘之前的，显示为‘****’，示例：toby****@hstong.com
                        E_MAIL_mark=maskEmail(E_MAIL);
                    } catch (Exception e) {
                        log.error("E_MAIL密文解析处理异常" + e.getMessage());
                        E_MAIL_mark = "";
                    }
                }

                if(open_id_enc==''||open_id_enc==null){
                    log.debug("open_id为空,密文解析为空！");
                    open_id_mark = "";
                }else{
                    try{
                        open_id = DecryptUtil.decrypt(open_id_enc);
                        //whatsapp账号：从右往前数，第五位到第七位脱敏用“*”展示，其余明文
                        open_idlenth=open_id.length();
                        open_id_mark=open_id.substring(0,open_idlenth-7)+"***"+open_id.substring(open_idlenth-4,open_idlenth);
                    } catch (Exception e) {
                        log.error("open_id密文解析处理异常" + e.getMessage());
                        open_id_mark ="";
                    }
                }

                log.debug("customer_guid:"+customer_guid+"  mobile:"+mobile+"    E_MAIL:"+E_MAIL+"    open_id:"+open_id);
                log.debug("customer_guid:"+customer_guid+"  mobile_mark:"+mobile_mark+"    E_MAIL_mark:"+E_MAIL_mark+"    open_id_mark:"+open_id_mark);

                custarr = new String[4];
                custarr[0]=customer_guid;
                custarr[1]=mobile_mark;
                custarr[2]=E_MAIL_mark;
                custarr[3]=open_id_mark;
                markarray.add(custarr);
            }
            outData.put("result",1);
            outData.put("message","处理成功");
            outData.put("data",markarray);

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            outData.put("result",-1);
            outData.put("message","处理成功");
            outData.put("data","[]");
        }
        //log.debug("处理完成返回结果:" + outData);

        return outData;
    }

    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        log.debug("解析-k=" + getKey + " v=" + Rev_Value);
        return Rev_Value;
    }


    // 非空校验isNull
    public static boolean isNull(String value) {

        boolean reFlag = true;
        if (value == "" || value.length() <= 0) {
            reFlag = true;
        } else {
            reFlag = false;
        }
        log.debug(reFlag);
        return reFlag;
    }

    // 非空校验isNullMSG
    public static String isNullMSG(String key, String value) {

        String reResult = "";
        if (value == "" || value.length() <= 0) {
            reResult = key + "必填字段;";
        }
        return reResult;
    }

    public static String maskEmail(String email) {
        if (email == null || email.isEmpty() || !email.contains("@")) {
            return email;
        }
        int index = email.indexOf("@");
        int length = email.length();
        String maskedEmail;
        if(index>4) {
            maskedEmail = email.substring(0, 4); // 保留前四个字符
        }else {
            maskedEmail = email.substring(0, 1); // 保留第一个字符
        }
        for (int i = 1; i < index; i++) {
            maskedEmail += "*"; // 替换前缀部分
        }
        maskedEmail += email.substring(index); // 添加"@"及其后面的部分
        return maskedEmail;
    }

}
